<template>
  <div>
    <!--行内表单-->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchInfo" placeholder="请输入用户名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button  @click="getUserTable">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button  @click="addHandler" type="primary" v-if="hasAuth('sys:user:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <template>
          <el-popconfirm title="确定删除选中的用户吗？" @confirm="deleteHandler(null)">
            <el-button slot="reference" type="danger" :disabled="deleteStatus"
                       v-if="hasAuth('sys:user:delete')">批量删除</el-button>
          </el-popconfirm>
        </template>
      </el-form-item>

      <!--表格-->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="头像" width="50" prop="avatar">
          <template slot-scope="scope">
            <el-avatar :src="scope.row.avatar" size="small"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="158"></el-table-column>
        <el-table-column prop="roles" width="176" label="角色名称">
          <template slot-scope="scope">
            <template v-for="role in scope.row.roles">
              <el-tag type="info" size="small">{{role.name}}</el-tag>
              <span>  </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="158"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="158"></el-table-column>
        <el-table-column prop="status" label="状态" width="68">
          <template slot-scope="scope">
            <div  style="text-align: center">
              <el-tag size="small" v-if="scope.row.status===1" type="success">正常</el-tag>
              <el-tag size="small" v-else-if="scope.row.status===0" type="danger">禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created" label="创建时间" width="158"></el-table-column>
        <el-table-column prop="" label="操作" width="280">
          <template slot-scope="scope">
            <el-button type="text" @click="roleHandler(scope.row.id)">分配角色</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" @click="resetPassword(scope.row.id,scope.row.username)">重置密码</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" @click="editHandler(scope.row.id)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <template>
              <el-popconfirm title="确定删除吗？" @confirm="deleteHandler(scope.row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <!--分页组件-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="current"
      :page-size="size"
      :total="total">
    </el-pagination>

    <!--对话框-->
    <el-dialog :title="addFormStatus==='add'?'新增用户':'编辑用户'" :visible.sync="dialogVisible_add" width="600px" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" class="demo-addForm">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
          <el-alert v-if="addFormStatus==='add'" title="初始密码为888888" :closable="false" type="info" style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="100px">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('addForm')">提交</el-button>
          <el-button @click="resetForm('addForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--分配角色对话框-->
    <el-dialog title="分配角色" :visible.sync="dialogVisible_role" width="600px" :close-on-click-modal="false">
      <el-form :model="roleForm">
        <el-tree
          :data="treeData"
          show-checkbox
          node-key="id"
          ref="roleTree"
          :props="defaultProps">
        </el-tree>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_role = false">取 消</el-button>
        <el-button type="primary" @click="giveRoleHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
      name: "UserManage",
      data(){
        return {
          searchInfo:"",
          tableData: [], //表格中的数据
          multipleSelection: [],  //表格中勾选的项目
          deleteStatus:true,   //批量删除按钮的可选中状态
          current:null, //当前页码
          size:null,  //每页显示的条数
          total:null, //数据总数
          dialogVisible_add:false,  //新增对话框
          dialogVisible_role:false,  //分配角色对话框
          addFormStatus:"", //表单状态，添加还是编辑
          addForm:{},
          roleForm:{},
          treeData:[],  //树形控件的数据
          defaultProps: {   //树形控件子节点和结点标签的默认名称
            children: 'children',
            label: 'name'
          },
          rules: {
            username: [
              { required: true, message: '请输入用户名', trigger: 'blur' }
            ],
            email: [
              { required: true, message: '请输入邮箱', trigger: 'blur' }
            ],
            status: [
              { required: true, message: '请选择状态', trigger: 'change' }
            ]
          }
        }
      },
      methods:{
        addHandler(){   //新增功能
          this.dialogVisible_add = true;
          this.addFormStatus = "add";
          this.resetForm("addForm");
        },
        editHandler(id){  //编辑功能
          this.addFormStatus = "edit";
          this.dialogVisible_add = true;
          this.axios.get("/sys/user/info/"+id).then(res=>{
            this.addForm = res.data.data;
          })
        },
        deleteHandler(id){  //删除功能
          let Ids = [];
          if(id!=null){ //单条删除
            Ids.push(id);
          }else {       //批量删除
            this.multipleSelection.forEach(item=>{
              Ids.push(item.id);
            })
          }
          this.axios.post("/sys/user/delete",Ids).then(res=>{
            this.getUserTable();
            this.$message({
              message: '删除成功',
              type: 'success',
              onClose: () => { //消息框关闭时的回调函数
              }
            });
          })
        },
        handleSelectionChange(val) {  //表格选中状态改变时执行
          this.deleteStatus = val.length===0;    //没有被选中的项目时设置批量删除按钮不可选中
          this.multipleSelection = val;
        },
        roleHandler(id){  //分配角色功能
          this.dialogVisible_role = true;
          this.axios.get("/sys/role/list").then(res=>{  //获取角色系统列表
            this.treeData = res.data.data.records;
          })

          this.axios.get("/sys/user/info/"+id).then(res=>{  //选中用户已有角色
            this.roleForm = res.data.data;    //方便提交时的操作，通过this.permForm.id获取要修改的用户
            let roles = res.data.data.roles;
            let roleIds = [];
            roles.forEach(role=>{
              roleIds.push(role.id)
            })
            this.$refs.roleTree.setCheckedKeys(roleIds);
          })
        },
        giveRoleHandler(){  //提交分配的角色到后台
          let roleIds = this.$refs.roleTree.getCheckedKeys();
          this.axios.post("/sys/user/role/"+this.roleForm.id,roleIds).then(res=>{
            this.getUserTable();
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose:() => {
              }
            });
          })
          this.dialogVisible_role = false;
        },
        resetPassword(id,username){  //重置密码
          this.$confirm('将重置用户【' + username + '】的密码为888888，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.axios.post("/sys/user/repass", id).then(res => {
              this.$message({
                showClose: true,
                message: '操作成功',
                type: 'success',
                onClose: () => {
                }
              });
            })
          }).catch(() => {})
        },
        handleSizeChange(val){   //每页显示的条数改变时执行，页码功能，改变每页显示条数
          this.size = val;
          this.getUserTable();
        },
        handleCurrentChange(val){  //页码变动时执行，页码功能，切换页码
          this.current = val;
          this.getUserTable();
        },
        submitForm(formName){
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.axios.post('/sys/user/' + (this.addForm.id ? 'update' : 'save'), this.addForm).then(res => {
                this.getUserTable();
                this.$message({
                  showClose: true,
                  message: '操作成功',
                  type: 'success',
                  onClose: () => { //消息框关闭时的回调函数
                  }
                });
                this.dialogVisible_add = false;
              })
            } else {
            }
          });
        },
        resetForm(formName) {
          this.addForm = {};
        },
        getUserTable(){
          this.axios.get("/sys/user/list",{
            params: {
              name: this.searchInfo,
              current: this.current,
              size: this.size
            }
          }).then(res=>{
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
            this.size = res.data.data.size;
            this.current = res.data.data.current;
          })
        }
      },
      created() {
        this.getUserTable();
      }
    }
</script>

<style scoped>
.el-pagination{
  float: right;
  margin-top: 16px;
}
</style>
